package com.crm.framework.interceptor.impl;

import com.crm.common.constant.Constants;
import com.crm.common.core.redis.RedisCache;
import com.crm.common.enums.ErrorCodeConstants;
import com.crm.common.exception.CustomException;
import com.crm.common.utils.StringUtils;
import com.crm.common.utils.sign.SignUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

@Component
public class CheckSignInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisCache redisCache;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {

        String sign = request.getParameter("sign");
        String iden = request.getParameter("iden");
        String timestamp = request.getParameter("timestamp");
        if(StringUtils.isBlank(sign) || StringUtils.isBlank(iden) || StringUtils.isBlank(timestamp)){
            throw new CustomException(ErrorCodeConstants.CONFIG_MISSING.getMsg(),ErrorCodeConstants.CONFIG_MISSING.getCode());
        }
        Map<String, String[]> paramMap =  request.getParameterMap();
        Map<String, String> signMap = new HashMap<>();
        for(String key : paramMap.keySet()){
            if(!"sign".equals(key)){
                signMap.put(key,paramMap.get(key)[0]);
            }
        }
        String secretkey = redisCache.getCacheMapValue(Constants.SIGN_SECRETKEY, iden);
        String signStr = SignUtil.getSign(signMap, secretkey);
        if(!sign.equalsIgnoreCase(signStr)){
            throw new CustomException(ErrorCodeConstants.SIGN_ERROR.getMsg(),ErrorCodeConstants.SIGN_ERROR.getCode());
        }
        return true;
    }

}
